﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxCallback;

namespace TireService.Web.View.ServiceView
{
    public partial class ServiceCompletion : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            if (Page.IsPostBack != true)
            {
                
            }

            // Bind container data to gridview
            BindServiceForCompletionData(db, DateTime.Now);

            // Change gridview pagesize based on dropdownlist
            gvServiceCompletion.SettingsPager.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);

            // Dispose connection to database
            db.Dispose();
        }

        // <summary>
        /// Function that bind servicecarschedule that should have been completed to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="Scheduledate">Date that indicates that servicedetails should be before this date</param>
        private void BindServiceForCompletionData(TireServiceDB db, DateTime ScheduleDate)
        {
            gvServiceCompletion.DataSource = db.ServiceCarScheduleDetailViews.Where(p => p.ScheduleDate <= ScheduleDate & p.CarId != null & p.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.ServiceDrive & p.WorkCompleted == false).OrderBy(p => p.ScheduleDate).ToList();
            gvServiceCompletion.DataBind();

            GroupOrderData(Convert.ToInt32(ddlView.SelectedValue));
        }

        #region Private Functions

        /// <summary>
        /// Function that change grouping in order gridview
        /// </summary>
        /// <param name="ViewIndex">Integer setting the grouping mode</param>
        protected void GroupOrderData(int ViewIndex)
        {
            gvServiceCompletion.ClearSort();
            gvServiceCompletion.GroupSummary.Clear();
            switch (ViewIndex)
            {
                case 0:

                    gvServiceCompletion.GroupBy(gvServiceCompletion.Columns["ScheduleDate"]);
                    gvServiceCompletion.GroupBy(gvServiceCompletion.Columns["ContainerNumber"]);
                    gvServiceCompletion.GroupBy(gvServiceCompletion.Columns["ServiceCarDescription"]);

                    break;
                case 1:
                    gvServiceCompletion.GroupBy(gvServiceCompletion.Columns["ScheduleDate"]);
                    gvServiceCompletion.GroupBy(gvServiceCompletion.Columns["ContainerNumber"]);
                    gvServiceCompletion.GroupBy(gvServiceCompletion.Columns["CargoRoomNumber"]);

                    break;
            }
            gvServiceCompletion.ExpandAll();
        }

        #endregion

        #region Control Functions

        /// <summary>
        /// Button function for export of gridview
        /// </summary>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (ddlExport.Value == "0")
            {
                gvExport.WritePdfToResponse();
            }

            if (ddlExport.Value == "1")
            {
                gvExport.WriteXlsToResponse();
            }

            if (ddlExport.Value == "2")
            {
                gvExport.WriteCsvToResponse();
            }

            if (ddlExport.Value == "3")
            {
                gvExport.WriteRtfToResponse();
            }
        }

        /// <summary>
        /// Dropdown list function that change gridview grouping when selected item is changed
        /// </summary>
        protected void ddlView_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Group data
            GroupOrderData(Convert.ToInt32(ddlView.SelectedValue));
        }

        /// <summary>
        /// Callback function that handles completion of servicedrives
        /// </summary>
        protected void callMarkServiceCompleted_Callback(object sender, CallbackEventArgs e)
        {
            // Get values (0: Actionparameter, 1-X: Array of servicecarscheduledetailid's)
            string[] param = e.Parameter.Split(',');

            // Instantiate database
            TireServiceDB db = new TireServiceDB();

            // Get UserId
            Guid userid = new Guid(Membership.GetUser().ProviderUserKey.ToString());

            // Validate action to take
            if (Convert.ToString(param[0]) == "MarkCompletedNoEmail")
            {
                // Mark service drives as completed, but without sending email to customer
                for (int i = 1; i < param.Length; i++)
                {
                    TaskBLL taskBLL = new TaskBLL();
                    taskBLL.MarkServiceDriveAsCompletedByServiceCarScheduleDetailId(db, Convert.ToInt32(param[i]), false, false, false, userid, false);
                }

                // Commit changes to database - done in one transaction (can be done due to no email is send to customer)
                db.SubmitChanges();
            }
            if (Convert.ToString(param[0]) == "MarkCompletedSendEmail")
            {
                //string CustomerFeedbackURL = ConfigurationManager.AppSettings["CustomerFeedbackURL"].ToString();

                // Mark service drives as completed and send email to customer
                for (int i = 1; i < param.Length; i++)
                {
                    // Submit for each task (to avoid email being send out where database changes is not done)
                    TaskBLL taskBLL = new TaskBLL();
                    taskBLL.MarkServiceDriveAsCompletedByServiceCarScheduleDetailId(db, Convert.ToInt32(param[i]), true, false, true, userid, false);
                }
            }

            // Dispose database connection
            db.Dispose();
        }

        #endregion


        #region GridView Functions

        /// <summary>
        /// Postback function that updates gridview with servicedrives
        /// </summary>
        protected void gvServiceCompletion_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();
            
            // Bind container data to gridview
            BindServiceForCompletionData(db, DateTime.Now);

            db.Dispose();
        }

        /// <summary>
        /// Gridview function that change field data for unbound fields
        /// </summary>
        protected void gvServiceCompletion_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            // Format UnBoundColumn TireDimensions: Show TireDimensions
            if (e.Column.FieldName == "TireDimensions")
            {
                // Get dimensions
                string width = Convert.ToString(e.GetListSourceFieldValue("Width"));
                string height = Convert.ToString(e.GetListSourceFieldValue("Height"));
                string size = Convert.ToString(e.GetListSourceFieldValue("Size"));

                // Change field value
                e.Value = width + " / " + height + " " + size;
            }
        }

        protected void gvTaskDetail_DataSelect(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();
            ASPxGridView gvTaskDetail = (sender as ASPxGridView);
            gvTaskDetail.DataSource = db.GetTaskDetailsExtendedView(Convert.ToInt32((sender as ASPxGridView).GetMasterRowKeyValue()));

            db.Dispose();
        }


        #endregion

    }
}